package middleware

import (
	"bytes"
	"encoding/json"
	"gbox-one-machine/conf"
	"gbox-one-machine/log"
	"github.com/gin-gonic/gin"
	"io/ioutil"
)

type httpReqInfo struct {
	Proto      string `json:"proto"`
	RemoteAddr string `json:"remote-addr"`
	Method     string `json:"method"`
	URI        string `json:"uri"`
	UserAgent  string `json:"user-agent"`
	Body       string `json:"body"`
}

// BaseMiddleware for gin
func BaseMiddleware(cf *conf.Config) func(c *gin.Context) {
	return func(c *gin.Context) {
		if cf.App.Debug {
			body, _ := c.GetRawData()

			req := &httpReqInfo{
				Proto:      c.Request.Proto,
				RemoteAddr: c.Request.RemoteAddr,
				Method:     c.Request.Method,
				URI:        c.Request.RequestURI,
				UserAgent:  c.Request.UserAgent(),
				Body:       string(body),
			}

			reqJSON, _ := json.MarshalIndent(req, "", "  ")
			log.Logger.Debugf("Request:\n%s", reqJSON)
			c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
		}
		c.Next()
	}
}
